/*
 * Copyright (c) 2012 Universidad Antonio de Nebrija.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0
 * which accompanies this distribution, and is available at
 * http://www.apache.org/licenses/LICENSE-2.0.html
 * 
 * Contributors:
 *    Universidad Antonio de Nebrija - initial API, implementation and documentation
 */
package com.nebrija.riif.model.functions.timeline;


import com.nebrija.riif.model.Function;
import com.nebrija.riif.model.RootClass;
import com.nebrija.riif.model.TimeStrings;
import com.nebrija.riif.model.Timeline;
import com.nebrija.riif.model.ValueTimeUnit;


/**
 * Function for get time
 * @author asanchep
 *
 */
public class GetTimeSince extends Function{

	
		public static final String NAME="timeline.get_time_since";
		
		/**
		 * Creates an object
		 */
		public GetTimeSince() {
			super(GetTimeSince.NAME, 2);
		}

		protected Object executeFunction(Object... operands) {
			// there must be at least one operand with the number of failures to compare to
			if (operands.length!=2){
				return keepString(operands);
			}
			Timeline timeline = RootClass.getInstance().getGlobalTimeline();
			ValueTimeUnit vtu = null;
			vtu= (operands[0] instanceof String)?ValueTimeUnit.stringToVTU((String)operands[0]):(ValueTimeUnit)operands[0];
			TimeStrings ts = TimeStrings.valueOf(((String)operands[1]).replaceAll("\"",""));
			if (timeline==null){
				return keepString(operands);
			}
			Double res = timeline.getTimeSince(vtu,ts);
			if(res==null){
				return keepString(operands);
			}
			return res;

		}
		
		/**
		 * Returns the original string
		 * @param operands the original operands
		 * @return the string
		 */
		protected Object keepString(Object[] operands){
			StringBuilder notResolved = new StringBuilder(operands[0].toString());
			for (int i=1; i<operands.length; i++){
				notResolved.append(",").append(operands[i].toString());
			}
			return NAME+"("+notResolved.toString()+")";
		}
		
}